package be.tf.freemaind.service;

import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Statement;

public class TreeGenerator {

static final String sqlNode="select c.idCategory,c.name as cname," +
		"c.description as cdescription,f.idclef,f.name as fname," +
		"f.description as fdescription,idpost,title,file,p.description as pdescription " +
		",sdate,pdate from Post p "+ 
		"inner join Category c on c.IdCategory=p.Category_IdCategory "+
		"inner join clef f on f.idclef=p.clef_idclef "+
		"order by IdCategory,Idclef;";


public String xmlMap(Statement stm) {
	String mindMap=	"<map versin=\"0.9.0\"><node CREATED=\"1309871265946\" ID=\"ID_60360302\" MODIFIED=\"1309871274371\">" +
					"<richcontent TYPE=\"NODE\"><html><img src=\"images/homepage_icon2.jpg\" /></html></richcontent>"+
					"<edge COLOR=\"#0033ff\" />";
	
	try {
		ResultSet rs = stm.executeQuery(sqlNode);
		
		int currentCat=0;
		int currentClef=0;
		int i=0;
		while (rs.next()) {
			i++;
			if (currentCat!=rs.getInt("idCategory")){
				
				//close previous node
				if(currentCat!=0) {
					mindMap=mindMap+"</node></node>";
					currentClef=0;
				}
				currentCat=-1;
				
				int modulo = i % 2; 
				//write new category node
				if (modulo==1) {
					mindMap=mindMap+"<node CREATED=\"1309871265946\" ID=\""+rs.getInt("idCategory")+
							"\" COLOR=\"#0033ff\" MODIFIED=\"1309871265946\" POSITION=\"left\" TEXT=\""+
							rs.getString("cname")+"\"><edge COLOR=\"#0033ff\" />";
				} else {
					mindMap=mindMap+"<node CREATED=\"1309871265946\" ID=\""+rs.getInt("idCategory")+
							"\" COLOR=\"#0033ff\" MODIFIED=\"1309871265946\" TEXT=\""+
							rs.getString("cname")+"\"><edge COLOR=\"#0033ff\" />";
				}
//				mindMap=mindMap+"<node CREATED=\"1309871265946\" ID=\""+rs.getInt("idCategory")+"\" COLOR=\"#0033ff\" MODIFIED=\"1309871265946\""+" POSITION=\"left\" TEXT=\""+rs.getString("cname")+"\"><edge COLOR=\"#0033ff\" />";

			}
			if (currentClef!=rs.getInt("idclef")){
				//close previous node
				if(currentClef!=0) mindMap=mindMap+"</node>";
				//create new node clef
				mindMap=mindMap+"<node CREATED=\"1309871265946\" ID=\""+
						rs.getInt("idclef")+"\" COLOR=\"#00b439\" MODIFIED=\"1309871265946\" FOLDED=\"true\" TEXT=\""+
						rs.getString("fname")+"\"><edge COLOR=\"#00b439\" />";	
			}
			//create leaf node (POST)
			mindMap=mindMap+"<node CREATED=\"1309961866264\" ID=\""+rs.getString("idpost")+"\""+
					" LINK=\"Post?id="+rs.getString("idpost")+"\""+
					" COLOR=\"#ff0000\">"+				
					"<edge COLOR=\"#ff0000\" /><richcontent TYPE=\"NODE\"><html><img src=\"images/"+
					rs.getString("file")+"\" height=\"90\" width=\"90\"/><p>"+rs.getString("title")+
					"</p></html></richcontent></node>";
			
			currentCat=rs.getInt("idCategory");
			currentClef=rs.getInt("idclef");	
					
		}
		rs.close();

		
	} catch (SQLException e) {
		e.printStackTrace();
	}
	return mindMap+"</node></node></node></map>";
}
 

}
